package com.education.ai.service.impl;

import com.education.ai.service.AiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AiServiceImpl implements AiService {

    @Autowired
    @Qualifier("qwenWebClient")
    private WebClient qwenWebClient;
    
    @Autowired
    private ObjectMapper objectMapper;
    
    @Value("${qwen.model:qwen-max}")
    private String model;

    @Override
    public String generateContent(String prompt) {
        try {
            // 构建API请求
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", model);
            requestBody.put("prompt", prompt);
            requestBody.put("result_format", "text");
            
            log.debug("发送到API的请求: {}", requestBody);
            
            // 调用通义千问API
            String responseJson = qwenWebClient.post()
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .block();
            
            log.debug("API响应: {}", responseJson);
            
            // 解析API响应
            JsonNode rootNode = objectMapper.readTree(responseJson);
            if (rootNode.has("output") && rootNode.get("output").has("text")) {
                return rootNode.get("output").get("text").asText();
            } else {
                log.error("API响应格式不符合预期: {}", responseJson);
                throw new RuntimeException("API响应格式不符合预期");
            }
        } catch (Exception e) {
            log.error("调用AI服务时发生错误", e);
            throw new RuntimeException("调用AI服务失败: " + e.getMessage(), e);
        }
    }
} 